package com.crowntit.domain.trade.service.lock.filter;

import com.crowntit.domain.trade.adapter.repository.ITradeRepository;
import com.crowntit.domain.trade.model.entity.GroupBuyActivityEntity;
import com.crowntit.domain.trade.model.entity.TradeLockRuleBackEntity;
import com.crowntit.domain.trade.model.entity.TradeLockRuleCommandEntity;
import com.crowntit.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import com.crowntit.types.design.framework.link.model2.handler.ILogicHandler;
import com.crowntit.types.enums.ActivityStatusEnumVO;
import com.crowntit.types.enums.ResponseCode;
import com.crowntit.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class TradeLockActivityUsabilityFilter implements ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleBackEntity> {

    @Resource
    private ITradeRepository repository;

    @Override
    public TradeLockRuleBackEntity apply(TradeLockRuleCommandEntity requestParam, TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        GroupBuyActivityEntity groupBuyActivityEntity = repository.queryGroupBuyActivityByActivityId(requestParam.getActivityId());

        Integer status = groupBuyActivityEntity.getStatus();
        if (!ActivityStatusEnumVO.EFFECTIVE.getCode().equals(status)){
            log.info("活动不在生效状态，活动id: {} ，当前状态: {}", requestParam.getActivityId(), status);
            throw new AppException(ResponseCode.E0101.getCode(), ResponseCode.E0101.getInfo());
        }

        Date current = new Date();
        Date startTime = groupBuyActivityEntity.getStartTime();
        Date endTime = groupBuyActivityEntity.getEndTime();
        if (current.after(endTime) || current.before(startTime)){
            log.info("不在活动时间，活动id: {} ，当前时间: {} ，活动时间: {} ~ {} ", requestParam.getActivityId(), current, startTime, endTime);
            throw new AppException(ResponseCode.E0102.getCode(), ResponseCode.E0102.getInfo());
        }

        dynamicContext.setGroupBuyActivity(groupBuyActivityEntity);
        return next(requestParam, dynamicContext);
    }
}
